package com.dic.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.dic.common.vo.es.SkuEsModel;
import com.dic.mall.search.config.ElasticSearchConfig;
import com.dic.mall.search.constant.EsConstant;
import com.dic.mall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：leeliang
 * @date ：Created in 2021/3/12 1:38
 * @description：
 * @modified By：
 * @version: $
 */
@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModelList) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        if(!b){
            log.info("商品上架成功");
        }else{
            log.error("商品上架失败");
        }
        BulkItemResponse[] items = bulk.getItems();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());

        log.info("上架数据有{}",collect);
        return !b;
    }
}
